package com.ybfenpan.controller;

import com.ybfenpan.controller.core.BaseController;
import com.ybfenpan.model.Daili;
import com.ybfenpan.model.Member;
import com.ybfenpan.response.Resp;
import com.ybfenpan.service.DailiService;
import com.ybfenpan.service.MemberService;
import com.ybfenpan.service.ParamWageService;
import com.ybfenpan.utils.CryptUtil;
import com.ybfenpan.utils.MapUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lzx on 2017/5/26.
 */
@Controller
public class RegisterController extends BaseController {


    @Resource
    private MemberService memberService;
    @Resource
    private DailiService dailiService;
    @Resource
    private ParamWageService paramWageService;


    @GetMapping("/qrcode/{id}.shtml")
    public String qrcodeRegister(@PathVariable String id, Model model) {

        Member member = memberService.executMemberByLoginName(id);
        if (member != null) {

            model.addAttribute("recommendLoginName", member.getLoginName());
            List<Daili> dailis = dailiService.queryForList("select", null);
            model.addAttribute("dailiList", dailis);
            model.addAttribute("qrcode", id);
            return "qrcodeRegister";
        }

        return "redirect:/";
    }

    @RequestMapping("qrcodeRegister.shtml")
    @ResponseBody
    public Resp add(HttpServletRequest request) throws Exception {
        Map formMap = getParameterMap(request);


        /*****************验证******************/

        boolean result = true;
        String message = "";
        //账号
        String loginName = MapUtil.getString(formMap, "loginName");

        if (loginName == null || loginName.length() < 6) {
            message = "账户必须大于6位。";
            return new Resp(-1, message);
        }
        if (memberService.executMemberByLoginName(loginName) != null) {
            message = "该代理商账号已经存在。";
            result = false;
        }


        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(loginName);
        if (matcher.find()) {
            message = "登录名不能包含中文。";
            result = false;

        }
        //过滤登录名的特殊字符
        if (loginName.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() != 0) {

            message = "该登录名含有特殊字符，请重新填写！";
            result = false;
        }

        if (loginName.length() > loginName.replaceAll(" ", "").length()) {
            message = "该登录名含有空格，请重新填写！";
            result = false;
        }

        // 服务中心
        String baodanLoginName = MapUtil.getString(formMap, "centerLoginName");
        Integer centerId = null;
        Member center = null;
        if (!baodanLoginName.equals("") && baodanLoginName != null) {
            center = memberService.executMemberByLoginName(baodanLoginName);
            if (center != null) {
                if (center.getAccountCenter().equals("F")) {
                   message= "服务中心编号不正确或者该代理商不是服务中心！";
                    result = false;
                } else {
                    centerId = center.getId();
                }
            } else {
                message= "服务中心不存在！";
                result = false;
            }
        } else {
            message= "服务中心不能为空！";
            result = false;
        }

        // 接点人
        String fatherLoginName = MapUtil.getString(formMap, "fatherLoginName");
        Integer qu = MapUtil.getInteger(formMap,"qu");
        Integer fatherId = null;

        if (!fatherLoginName.equals("") && fatherLoginName != null) {
            Member father = memberService.executMemberByLoginName(fatherLoginName);
            if (father != null) {

                if (qu == 1) {
                    if (father.getZuoId() != null) {
                       message= "该接点人左区已经有人了，如果已经注册，请先报单。";
                        result = false;
                    }
                }
                if (qu == 2) {
                    if (father.getYouId() != null) {
                        message="该接点人右区已经有人了，如果已经注册，请先报单。";
                        result = false;
                    }
                }

                if (father.getAccountActive().equals("F")) {
                    message="该接点人未报单，不能放置在该接点人下面。";
                    result = false;

                }

                fatherId = father.getId();
            } else {
                message="接点人不存在。";
                result = false;

            }
        }


        //推荐人
        String recommendLoginName = MapUtil.getString(formMap, "recommendLoginName");

        Integer recommendId = null;
        Member recommend;
        if (recommendLoginName != null && !recommendLoginName.equals("")) {
            recommend = memberService.executMemberByLoginName(recommendLoginName);
            if (recommend != null) {
                if (recommend.getAccountActive().equals("F")) {
                    message = "推荐人未报单。";
                    result = false;
                } else {
                    recommendId = recommend.getId();
                }
            } else {
                message = "推荐人不存在。";
                result = false;

            }
        } else {
            message = "推荐人不存在。";
            result = false;
        }

        int dailiId = MapUtil.getIntValue(formMap, "dailiId");
        Daili daili = dailiService.getByKey(dailiId);
        if(daili == null) {
            message = "代理商等级不存在";
            result = false;
        }


        String onePsw = MapUtil.getString(formMap, "onePassword");
        if (onePsw == null || onePsw.length() < 6) {
            message = "一级密码必须大于6位。";
            result = false;
        }


        String twoPsw = MapUtil.getString(formMap, "twoPassword");
        if (twoPsw == null || twoPsw.length() < 6) {
            message = "二级密码必须大于6位。";
            result = false;
        }


        if (!result) {

            return new Resp(-1, message);
        }


        String onePassword = CryptUtil.getInstance().encrypt2String(onePsw, CryptUtil.keyStr);
        String twoPassword = CryptUtil.getInstance().encrypt2String(twoPsw, CryptUtil.keyStr);


        Member one = new Member();

        one.setLoginName(loginName);
        one.setOnePassword(onePassword);
        one.setTwoPassword(twoPassword);
        one.setRecommendId(recommendId);
        one.setCenterId(centerId);
        one.setFatherId(fatherId);
        one.setQu(qu);
        one.setLevel(dailiId);

        one.setDailiId(dailiId);
        one.setPayNum(Double.valueOf(daili.getPayNum()));
        one.setCardNo(MapUtil.getString(formMap, "cardNo"));
        one.setRemark(MapUtil.getString(formMap, "remark"));
        one.setTel(MapUtil.getString(formMap, "tel"));
        one.setPersonName(MapUtil.getString(formMap, "personName"));
        one.setWei(MapUtil.getString(formMap, "wei"));
        one.setQq(MapUtil.getString(formMap, "qq"));

        one.setBankShi(MapUtil.getString(formMap, "bankShi"));
        one.setBankName(MapUtil.getString(formMap, "bankName"));
        one.setBankAddress(MapUtil.getString(formMap, "bankAddress"));
        one.setBankCardNo(MapUtil.getString(formMap, "bankCardNo"));
        one.setBankSheng(MapUtil.getString(formMap, "bankSheng"));
        one.setBankPersonName(MapUtil.getString(formMap, "bankPersonName"));


        memberService.saveOne(one);

        return new Resp(0, "注册成功，请尽快联系推荐人或者管理员进行报单", "/");
    }


    /**
     * loginName检测  ajax
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("qrcode/member/ajaxGetMemberByName.shtml")
    @ResponseBody
    public void ajaxGetMemberByName(HttpServletRequest request, HttpServletResponse response) {

        Map formMap = getParameterMap(request);
        String loginName = MapUtil.getString(formMap, "loginName");
        Member member = memberService.executMemberByLoginName(loginName);

        HashMap resultformMap = new HashMap();
        if (member == null) {

            renderSuccess(response, true, resultformMap);
        } else {

            renderSuccess(response, false, resultformMap);

        }
    }

}
